package com.ebupt.migu.music.schedule.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Objects;

@Slf4j
public class LockUtil {

    private RedisTemplate<String, Long> redisTemplate;

    private String key;

    private Long overTime = new Long(1000 * 60 * 10);

    private LockUtil(String key, RedisTemplate<String, Long> redisTemplate) {
        this.key = key;
        this.redisTemplate = redisTemplate;
    }

    public Boolean lock() {

        BoundValueOperations<String, Long> lock = redisTemplate.boundValueOps(key);
        log.info("加锁的key=====>{}", key);

        long nowTime = System.currentTimeMillis();
        log.info("加锁的时间=====>{}", nowTime);

        Long expireTime = lock.get();

        if (null != expireTime && (expireTime > nowTime)) {
            return false;
        }

        Long newTime = nowTime + overTime;

        Long oldTime = lock.getAndSet(newTime);

        if (null == oldTime || Objects.equals(expireTime, oldTime)) {
            return true;
        }

        return false;
    }

    public Boolean del() {
        log.info("解锁的key=====>{}", key);
        return redisTemplate.delete(key);
    }



    public Boolean query() {
        log.info("查询key=====>{}", key);
        return redisTemplate.hasKey(key);
    }


    public static LockUtil get(String key, RedisTemplate<String, Long> redisTemplate) {
        return new LockUtil(key, redisTemplate);
    }
}